package models;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import objects.Concept;
import objects.ConceptList;
import objects.Ontology;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

/* Accessible only through OntologyModel */
class OntologyXMLReader {
	
	private Ontology db;
	
	public OntologyXMLReader() {
		db = null;
	}
	
	public void read(String fileLocation) throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
		Document doc = docBuilder.parse(new File(fileLocation));
		
		db = (Ontology) getXML(doc.getDocumentElement());
	}
	
	public Object getXML(Node node) {
		Object created = null;
		
		if (node.getNodeName().equals("ontologylist")) {
			Ontology db = new Ontology();
			created = db;
		}
		else if (node.getNodeName().equals("pos")) {
			ConceptList conList = new ConceptList();
			
			Attr label = (Attr) node.getAttributes().getNamedItem("label");
			
			if (label != null) {
				conList.setLabel(label.getValue());
			}
			
			created = conList;
		}
		else if (node.getNodeName() == "ontology") {
			Concept con = new Concept();
			
			Attr concept = (Attr) node.getAttributes().getNamedItem("concept");
			Attr sense = (Attr) node.getAttributes().getNamedItem("sense");
			Attr definition = (Attr) node.getAttributes().getNamedItem("definition");

			if (concept != null) {
				con.setName(concept.getValue());
			}
			if (sense != null) {
				con.setSense(sense.getValue());
			}
			if (definition != null) {
				con.setDefinition(definition.getValue());
			}
			
			created = con;
		}

		if (node.hasChildNodes()) {
			for (int i = 0; i < node.getChildNodes().getLength(); i++) {
				Object returnedType = getXML(node.getChildNodes().item(i));

				if (returnedType != null) {
					if (returnedType.getClass().getName() == "objects.Concept") {
						ConceptList db = (ConceptList) created;
						Concept concept = (Concept) returnedType;
						
						db.addConceptListItem(concept);
					} 
					else if (returnedType.getClass().getName() == "objects.ConceptList") {
						Ontology db = (Ontology) created;
						ConceptList concept = (ConceptList) returnedType;
						
						db.addOntologyListItem(concept);
					} 
				}
			}
		}

		return created;
	}
	
	public ArrayList<ConceptList> getDatabase() {
		return db.getOntologyList();
	}

}
